#include "../logs/log.h"
#include <chrono>
void bench(const std::string &logger_name,size_t thr_count,size_t msg_count,size_t msg_len)
{
    //1. 获取日志器
    log::Logger::ptr logger = log::getLogger(logger_name);
    if(logger.get() == nullptr) return;
    std::cout << "日志测试: " << msg_count << "条，总大小: " << (msg_count * msg_len) /1024 << "KB\n";
    //2. 组织指定长度的日志消息
    std::string msg(msg_len-1,'A');
    //msg.resize(msg_len+1);
    //3. 创建指定数量的线程
    std::vector<std::thread> _threads;
    std:: vector<double> _costs;
    _costs.resize(thr_count);
    size_t msg_prt_thr = msg_count / thr_count; //总日志数量/线程数量就是每隔线程要输出的日志数量
    for(int i=0;i<thr_count;i++)
    {
        _threads.emplace_back([&,i]()
        {
            //4. 线程函数内部开始计时
            auto start = std::chrono::high_resolution_clock::now();
            //5. 开始循环写日志
            for(int j=0;j<msg_count;j++)
            {
                logger->fatal("%s-%d",msg.c_str(),j+1);
            }
            //6. 线程函数内部结束计时
            auto end = std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> cost = end-start;
            _costs[i] = cost.count();
            std::cout << "线程-" << i << ":" << "\t输出日志数量:" << msg_prt_thr << " 耗时:" << cost.count() << "s"
            <<std::endl;
        });
    }
    for(int i=0;i<thr_count;i++)
    {
        _threads[i].join();
    }
    //7. 计算总耗时 
    double max_cost = _costs[0];
    for(int i=0;i<thr_count;i++)
    {
        max_cost = std::max(max_cost,_costs[i]);
    }
    size_t msg_per_sec = msg_count / max_cost;
    size_t size_per_sec = msg_count * msg_len / (max_cost * 1024);
    //8. 进行输入打印
    std::cout << "每秒输出日志数量: " << msg_per_sec <<"条"<< std::endl;
    std::cout << "每秒输出日志大小: " << size_per_sec <<"KB"<< std::endl;

}

void sync_bench()
{
    std::shared_ptr<log::LoggerBuilder> builder(std::make_shared<log::GloballoggerBuilder>());
    //builder->buildLoggerLevel(log::LogLevel::value::DEBUG);
    builder->buildLoggerName("sync_logger");
    builder->buildLoggerType(log::Logger_type::LOGGER_SYNC);
    //builder->buildSink<log::StdoutSink>();
    //builder->buildEnableUnSafeAsync();
    builder->buildSink<log::FileSink>("./logfile/sync.log");
    log::Logger::ptr _logger= builder->build();
    bench("sync_logger",3,300000,100); //单线程下的同步日志器测试
    //bench("sync_logger",1,1000000,100);
}
void async_bench()
{
    std::shared_ptr<log::LoggerBuilder> builder(std::make_shared<log::GloballoggerBuilder>());
    //builder->buildLoggerLevel(log::LogLevel::value::DEBUG);
    builder->buildLoggerName("sync_logger");
    builder->buildLoggerType(log::Logger_type::LOGGER_ASYNC);
    //builder->buildSink<log::StdoutSink>();
    builder->buildEnableUnSafeAsync();
    builder->buildSink<log::FileSink>("./logfile/Async.log");
    builder->build();
    bench("sync_logger",3,1000000,100); //单线程下的同步日志器测试
}

int main()
{
    async_bench();
    return 0;
}